require(['init'], function () {
  var $pagination = $('#js-pagination');
  var pagination;

  function Admin(options) {
    options = options || {};
    this.data = options.data || {};
    this.$dom = $('<div class="formList"></div>');

    this.init(this.configList);
  }

  Admin.prototype = {
    configList: [
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>'+i18next.t('info.name')+'',//姓名
        content: {
          init: function ($content, root) {
            root.$nameInput = $('<input type="text" class="form-control" data-formcheck="length" style="width: 200px">').appendTo($content);
            root.$nameInput.on('change', function () {
              root.data.name = $.trim(root.$nameInput.val());
            })
          },
          update: function ($content, root, formData) {
            if(formData.name) {
              root.$nameInput.val(formData.name)
            }
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>'+i18next.t('table.mobilephone')+'',
        content: {
          init: function ($content, root) {
            root.$phoneInput = $('<input type="text" class="form-control" data-formcheck="phone" style="width: 200px">').appendTo($content);
            root.$phoneInput.on('change', function () {
              root.data.number = $.trim(root.$phoneInput.val());
            })
          },
          update: function ($content, root, formData) {
            if(formData.number) {
              root.$phoneInput.val(formData.number)
            }
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>'+i18next.t('info.email')+'',
        content: {
          init: function ($content, root) {
            root.$emailInput = $('<input type="text" class="form-control" data-formcheck="email" style="width: 200px">').appendTo($content);
            root.$emailInput.on('change', function () {
              root.data.email = $.trim(root.$emailInput.val());
            })
          },
          update: function ($content, root, formData) {
            root.$emailInput.val(formData.email)
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>'+i18next.t('table.position')+'',//职位
        content: {
          init: function ($content, root) {
            root.$posInput = $('<input type="text" class="form-control" data-formcheck="length" style="width: 200px">').appendTo($content);
            root.$posInput.on('change', function () {
              root.data.position = $.trim(root.$posInput.val());
            })
          },
          update: function ($content, root, formData) {
            root.$posInput.val(formData.position)
          }
        }
      },
      {
        title: '<span class="icon icon-size-16 icon-asterisk"></span>'+i18next.t('table.department')+'',//部门
        content: {
          init: function ($content, root) {
            root.$depInput = $('<input type="text" class="form-control" data-formcheck="length" style="width: 200px">').appendTo($content);
            root.$depInput.on('change', function () {
              root.data.department = $.trim(root.$depInput.val());
            })
          },
          update: function ($content, root, formData) {
            root.$depInput.val(formData.department)
          }
        }
      }
    ],
    createFormLi: function (liConfig) {
      var $formLi = $('<div class="formLi"></div>').appendTo(this.$dom);
      $('<div class="formTitle"></div>').html('<span class="titleText">'+ liConfig.title +'</span>').appendTo($formLi);
      var $formContent = $('<div class="formContent"></div>').appendTo($formLi);
      liConfig.content.init($formContent, this);
      if(liConfig.content.update) {
        liConfig.content.update($formContent, this, this.data);
      }
    },

    init: function (liConfigList) {
      $.each(liConfigList, function (i, cur) {
        this.createFormLi(cur)
      }.bind(this));
    }
  }


  function getAdminList(query, cb) {
    ajaxMethod({
      url: '/api/employees',
      data: query || {},
      success: function (data) {
        cb && cb(data)
        var $classlistTable = $('#J_classlist').html('')
        var $thead = $('<thead>\
          <tr>\
            <th>'+i18next.t('table.no')+'</th>\
            <th>'+i18next.t('info.name')+'</th>\
            <th>'+i18next.t('info.cellphonenumber')+'</th>\
            <th>'+i18next.t('info.email')+'</th>\
            <th>'+i18next.t('table.position')+'</th>\
            <th>'+i18next.t('table.department')+'</th>\
            <th style="width:200px">'+i18next.t('table.handle')+'</th>\
          </tr>\
        </thead>').appendTo($classlistTable)

        var $tbody = $('<tbody></tbody>').appendTo($classlistTable)

        $.each(data.list, function (index, item) {
          var $classItem = $('<tr class="enroll"></tr>')

          $classItem.append('<td>'+ (index+1) +'</td>')
          $classItem.append('<td>'+ item.name +'</td>')
          $classItem.append('<td>'+ item.number +'</td>')
          $classItem.append('<td>'+ item.email +'</td>')
          $classItem.append('<td>'+ item.position +'</td>')
          $classItem.append('<td>'+ item.department +'</td>')

          var $handleTd = $('<td></td>').appendTo($classItem)

          if(item.status == 0) {
            $classItem.addClass('disable')
            var $editbtn = $('<a><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('table.enabled')+'</span></a>').appendTo($handleTd)
            $editbtn.on('click', function () {
              ajaxMethod({
                url: '/api/employee/' + item.id + '/enable',
                method: 'put',
                success: function(data, status) {
                  if(status.code == 0) {
                    pagination.updateData()
                  }
                }
              })

            })

          } else {
            var $editbtn = $('<a class="ml5"><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('table.compile')+'</span></a>').appendTo($handleTd)
            $editbtn.on('click', function () {
              var admin = new Admin({
                data: {
                  name: item.name,
                  number: item.number,
                  email: item.email,
                  position: item.position,
                  department: item.department
                }
              })

              var popUpBox=new PopUpBox({
                type:'dom',
                style:'default contentScroll',
                submitBtnType:'confirm',
                titleText:i18next.t('table.compileagency'),//编辑机构人员
                drag:true,
                show: true,
                content: admin.$dom,
                callback:{
                  yes: function (e) {
                    var formCheckResult = FormCheck.childrenInputCheck(admin.$dom)
                    if(formCheckResult) {
                      ajaxMethod({
                        url: '/api/employee/' + item.id,
                        method: 'put',
                        data: admin.data,
                        success: function (data, status) {
                          if(status.code == 0) {
                            pagination.updateData()
                            popUpBox.close()
                          }
                        }
                      })
                    }

                    return false;
                  }
                },
                position:{
                  width:400,
                  height:400
                }
              })
            })

            var $deletebtn = $('<a href="javascript:;"><span class="btn btn-danger btn-sm btn-inverse">'+i18next.t('table.forbidden')+'</span></a>').appendTo($handleTd)
            $deletebtn.on('click', function () {
              var popUpBox = new PopUpBox({
                type: 'dom',
                style: 'default contentScroll',
                submitBtnType: 'confirm',
                titleText: '系统消息',
                show: true,
                content: '<div style="padding:30px"> '+i18next.t('popupbox.forbiddenadministrator')+'</div>',//确定禁用该管理员
                callback: {
                   yes: function (e) {
                     ajaxMethod({
                       url: '/api/employee/' + item.id + '/disable',
                       method: 'put',
                       success: function(data, status) {
                         if(status.code == 0) {
                           pagination.updateData()
                         }
                       }
                     })
                   }
                },
                position: {
                   width: 420,
                   height: 200
                }
              })
            })
          }
          permissionBtn($handleTd,item);
          $tbody.append($classItem)
        })
        $pagination.show()
      }
    })
  }
  function permissionBtn($parent, item) {
    var $wrapperDom = $('<div style="padding:20px"></div>')

    function loadAllRoles(data) {
      $wrapperDom.html('')
      $.each(data, function (i, role) {
        var $item = $('<div style="height:25px">\
            <span class="icon icon-size-16 icon-checkbox" data-type="checkbox">\
                <input id="id_'+ role.id +'" type="checkbox" name="gender">\
            </span><span data-type="label">'+ role.title +'</span>\
          </div>').appendTo($wrapperDom)
      })
    }

    function loadUserRoles(data) {
      $.each(data, function (i, item) {
        $wrapperDom.find('#id_'+ item.id +'').prop('checked', true).parent().addClass('checked')
      })
    }


    var $btn = $('<a><span class="btn btn-primary btn-sm btn-inverse">'+i18next.t('index.rolemanagement')+'</span></a>').appendTo($parent)
    $btn.on('click', function () {
      $.when(
          $.ajax('/api/authority/roles?status=1'),
          $.ajax('/api/authority/'+ item.userid +'/roles')
      ).done(function () {
        var cbFnArr = [
          loadAllRoles,
          loadUserRoles
        ]

        var resArr = [].slice.call(arguments,0,2)
        $.each(resArr, function (i, curRes) {
          if(curRes[1] == 'success') {
            cbFnArr[i](curRes[0].data)
          }
        })

        var popUpBox=new PopUpBox({
          type:'dom',
          style:'default contentScroll',
          submitBtnType:'confirm',
          titleText:i18next.t('table.edituserroles'),//编辑用户角色
          drag:true,
          show: true,
          content: $wrapperDom,
          callback:{
            yes: function (e) {
              var ids = []
              $wrapperDom.find('input:checked').each(function (i, item) {
                ids.push(Number(this.id.split('_')[1]))
              })

              ajaxMethod({
                url:  '/api/authority/userRoles',
                method: 'post',
                data: {
                  uid: item.userid,
                  roleids: ids
                },
                success: function (data, status) {
                  if(status.code == 0) {
                    pagination.updateData()
                    popUpBox.close()
                  }
                }
              })
              return false;
            }
          },
          position:{
            width: 420,
            height: 450
          }
        })
      })

    })
  }
  $('#js-add-admin').on('click', function () {
    var admin = new Admin()
    var popUpBox=new PopUpBox({
      type:'dom',
      style:'default contentScroll',
      submitBtnType:'confirm',
      titleText:i18next.t('table.addagency'),//添加机构人员
      drag:true,
      show: true,
      content: admin.$dom,
      callback:{
        yes: function (e) {
          var formCheckResult = FormCheck.childrenInputCheck(admin.$dom)
          if(formCheckResult) {
            ajaxMethod({
              url: '/api/employee',
              method: 'post',
              data: admin.data,
              success: function (data, status) {
                if(status.code == 0) {
                  pagination.updateData()
                  popUpBox.close()
                }
              }
            })
          }
          return false;
        }
      },
      position:{
        width:400,
        height:400
      }
    })
  })

  function loadSearchData(querystr) {
    if(querystr) {
      pagination.filter.email = querystr
      pagination.filter.account = querystr
      pagination.filter.number = querystr

      pagination.searchData()
    } else {
      pagination.reloadData()
    }
  }


  $('#J_search').on('click', function() {
    var $input = $(this).prev();
    var querystr = $.trim($input.val());
    loadSearchData(querystr)
  })

  $('.searchInput').on('keyup', function(e) {
    if(e.keyCode == 13) {
      var querystr = $.trim($(this).val());
      loadSearchData(querystr)
    }
  })

  pagination = new Pagination($pagination, getAdminList)

})
